using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TMS.Application.Common.Interface;
using TMS.Application.RequestDto;
using TMS.Domain.Entity;

namespace TMS.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class LoginController : ControllerBase
    {
        private readonly IRepository<StuUsers> _StuUsers;
        private readonly IRepository<TeaUsers> _TeaUsers;
        private readonly IRepository<Teachers> _Teachers;
        private readonly IRepository<Students> _Students;
        private readonly IFileUploadService _fileUploadService;//获取头像(暂且)


        /// <summary>
        /// 角色表判断是什么职位
        /// 
        /// 是否是管理员（IsMaster）bool 
        /// 是否是辅导员（IsInstructor）bool
        /// 是否是任课教师(IsTeacher) bool
        /// </summary>
        private readonly IRepository<Role> _Role;
        private readonly IIdentityService _IdentityService;



        public LoginController(IIdentityService IdentityService, IFileUploadService fileUploadService, IRepository<StuUsers> StuUsers, IRepository<TeaUsers> TeaUsers, IRepository<Teachers> Teachers, IRepository<Students> Students, IRepository<Role> Role)
        {
            _StuUsers = StuUsers;
            _TeaUsers = TeaUsers;
            _Teachers = Teachers;
            _Students = Students;
            _Role = Role;
            _fileUploadService = fileUploadService;
            _IdentityService = IdentityService;
        }
        [HttpPost("/login")]
        //需要学工号和密码
        public async Task<object> login(UserForAuthDto loginDto)
        {
            var UploadController = new UploadController(_fileUploadService);//用来获取头像

            if (loginDto.IsTea)
            {//教师登录
             //查找在教师表上是否有该用户
             //头像id在这张表中

                var loginUser = _TeaUsers.Table.Where(x => x.UserId == loginDto.UserId && x.PassWord == loginDto.Password).ToList();
                if (loginUser.Count == 1)
                {//有该用户
                    //查询教工的信息
                    var Teachers = _Teachers.Table.Where(x => x.TeacherId == loginUser[0].UserId).ToList();
                    //获取教工的头像
                    var Avatar = await UploadController.GetFile(loginUser[0].AvatarId);
                    //再查询在Role表上该教工的职位
                    var Role = _Role.Table.Where(x => x.TeacherId == Teachers[0].TeacherId).ToList();
                    //获取token
                    var token = await _IdentityService.ValidateUserAsync(loginDto);

                    var msg = new
                    {
                        Teachers=Teachers[0],
                        Teachers[0].Id,//教工id
                        Teachers[0].TeacherId,//教工号
                        Teachers[0].TeacherName,
                        Avatar.ContentType,
                        Avatar.FileContents,
                        Role[0].IsMaster,
                        Role[0].IsInstructor,
                        Role[0].IsTeacher   

                    };
                    return new
                    {
                        code=200,
                        msg="登录成功",
                        token,
                        data=msg
                    };
                }
                else
                {//查无该用户
                    return new
                    {
                        code = 400,
                        msg = "教工号或密码错误",
                        data = ""
                    };
                }
            }
            else
            {//学生登录
                //头像id在这张表中
                var StuUsers = _StuUsers.Table.ToList();
                //判断学生表中是否有该学生
                var loginUser = StuUsers.Where(x => x.UserId == loginDto.UserId && x.PassWord == loginDto.Password).ToList();

                if (loginUser.Count == 1)
                {//有该用户
                    //先获取所有学生ToList
                    var stu = _Students.Table.ToList();


                    //需要在Students表上拿取该学生信息
                    var student = stu.Where(x => x.StudentId == loginUser[0].UserId).ToList();
                    //获取学生头像
                    var Avatar = await UploadController.GetFile(loginUser[0].AvatarId);

                    //身份为学生所以不需要获取职位


                    var msg = new
                    {
                        student=student[0],
                        student[0].StudentId,//学号
                        student[0].StudentName,
                        // student[0].Sex,
                        // student[0].IdentityNumber,
                        // student[0].PhoneNumber,
                        // student[0].ChattingNumber,
                        // student[0].QQNumber,
                        // student[0].Address,                       
                        // student[0].FatherName,                       
                        // student[0].FatherPhone,                       
                        // student[0].MontherName,                       
                        // student[0].MontherPhone,                       
                        Avatar.ContentType,
                        Avatar.FileContents,
                        id=student[0].Id

                    };
                    //获取token
                    var token = await _IdentityService.ValidateUserAsync(loginDto);
                    return new
                    {
                        code = 200,
                        msg = msg,
                        data = "登录成功",
                        token
                    };
                }
                else
                {//查无该用户
                    return new
                    {
                        code = 400,
                        msg = "学号或密码错误",
                        data = ""
                    };
                }
            }
        }

        //教师修改密码
        [HttpPost("/TeacherChangePwd")]
        public async Task<object> TeacherChangePwd(ChangePwdDto changePwdDto)
        {
            var TeaUsers = _TeaUsers.Table.ToList();
            var tea = TeaUsers.Where(x => x.UserId == changePwdDto.UserId && x.PassWord == changePwdDto.OriginalPassword).FirstOrDefault();
            //查是否有该教工
            if (tea == null)
            {
                //没有该教工
                return new
                {
                    code = 400,
                    data = "",
                    msg = "教工号或密码错误"
                };

            }
            else
            {
                // 判断密码是否存在中文
                var IsCN = Regex.IsMatch(changePwdDto.SecondPassword, @"[\u4e00-\u9fa5]");
                if (changePwdDto.FirstPassword == "")
                {
                    return new
                    {
                        code = 400,
                        data = "",
                        msg = "密码不可为空！"
                    };
                }
                else if (changePwdDto.FirstPassword != changePwdDto.SecondPassword)
                {
                    return new
                    {
                        code = 400,
                        data = "",
                        msg = "密码不一致！"
                    };
                }
                else
                {

                    if (changePwdDto.SecondPassword.Length < 6)
                    {
                        return new
                        {
                            code = 400,
                            data = "",
                            msg = "密码长度不可小于6"
                        };
                    }
                    else if (IsCN)
                    {
                        return new
                        {
                            code = "400",
                            data = "",
                            msg = "密码中不可存在中文！"
                        };
                    }
                    else if (tea.PassWord == changePwdDto.SecondPassword)
                    {
                        return new
                        {
                            code = 400,
                            data = "",
                            msg = "新密码不可与原密码一致"
                        };
                    }
                    else
                    {
                        var newPassWord = tea;
                        newPassWord.PassWord = changePwdDto.SecondPassword;
                        await _TeaUsers.UpdateAsync(newPassWord);
                        return new
                        {
                            code = 200,
                            data = "",
                            msg = "密码修改成功"
                        };
                    }
                }

            }
        }
        //学生修改密码
        [HttpPost("/StudetnChangePwd")]
        public async Task<object> StudetnChangePwd(ChangePwdDto changePwdDto)
        {
            var StuUsers = _StuUsers.Table.ToList();
            var stu = StuUsers.Where(x => x.UserId == changePwdDto.UserId && x.PassWord == changePwdDto.OriginalPassword).FirstOrDefault();
            //查是否有该学生
            if (stu == null)
            {
                //没有该学生
                return new
                {
                    code = 400,
                    data = "",
                    msg = "学号或密码错误"
                };

            }
            else
            {
                // 判断密码是否存在中文
                var IsCN = Regex.IsMatch(changePwdDto.SecondPassword, @"[\u4e00-\u9fa5]");
                if (changePwdDto.FirstPassword == "")
                {
                    return new
                    {
                        code = 400,
                        data = "",
                        msg = "密码不可为空！"
                    };
                }
                else if (changePwdDto.FirstPassword != changePwdDto.SecondPassword)
                {
                    return new
                    {
                        code = 400,
                        data = "",
                        msg = "密码不一致！"
                    };
                }
                else
                {

                    if (changePwdDto.SecondPassword.Length < 6)
                    {
                        return new
                        {
                            code = 400,
                            data = "",
                            msg = "密码长度不可小于6"
                        };
                    }
                    else if (IsCN)
                    {
                        return new
                        {
                            code = "400",
                            data = "",
                            msg = "密码中不可存在中文！"
                        };
                    }
                    else if (stu.PassWord == changePwdDto.SecondPassword)
                    {
                        return new
                        {
                            code = 400,
                            data = "",
                            msg = "新密码不可与原密码一致"
                        };
                    }
                    else
                    {
                        var newPassWord = stu;
                        newPassWord.PassWord = changePwdDto.SecondPassword;
                        await _StuUsers.UpdateAsync(newPassWord);
                        return new
                        {
                            code = 200,
                            data = "",
                            msg = "密码修改成功"
                        };
                    }
                }

            }
        }
    }
}